<template>
  <div class="video-card-wrapper">
    <div class="video-container" @click="handleVideoClick">
      <video ref="videoPlayerRef" :src="videoPlayUrl" loop :poster="video?.cover?.detail || video?.cover?.feed"
        class="video-player" autoplay muted playsinline @play="handleVideoPlay" @pause="handleVideoPause"
        @loadedmetadata="handleVideoLoaded" @timeupdate="handleTimeUpdate"></video>
      <div v-if="showPlayIcon" class="play-icon-overlay">
        <van-icon name="play" class="play-icon-large" />
      </div>
    </div>

    <div class="info-bar" :class="{ hidden: !showInfo || showComment }" @click.stop>
      <div class="info-content">
        <div v-if="video?.author?.name" class="author-name">
          @{{ video.author.name }}
        </div>
        <div v-if="description" class="description-wrapper">
          <div ref="descElement" class="description" :class="{ 'expanded': isDescExpanded }">
            {{ description }}
          </div>
          <div v-if="showExpandButton" class="expand-btn" @click.stop="toggleDescExpand">
            {{ isDescExpanded ? '收起' : '展开' }}
          </div>
        </div>
      </div>

      <div class="action-bar">
        <div class="user-avatar-section">
          <div class="avatar-wrapper">
            <img :src="video?.author?.icon || ''" class="avatar" />
          </div>
          <div v-if="!isFollowed" class="follow-btn" @click.stop="handleFollow">
            <van-icon name="plus" class="follow-icon" />
          </div>
        </div>
        <div class="action-item" @click.stop="handleCollection" :class="{ 'liked': isLiked }">
          <van-icon :name="isLiked ? 'like' : 'like-o'" class="action-icon" />
          <span class="action-text">{{ displayCollectionCount }}</span>
        </div>
        <div class="action-item" @click.stop="handleReply">
          <van-icon name="chat-o" class="action-icon" />
          <span class="action-text">{{ displayReplyCount }}</span>
        </div>
        <div class="action-item" @click.stop="handleFavorites" :class="{ 'favorited': isFavorited }">
          <van-icon :name="isFavorited ? 'star' : 'star-o'" class="action-icon" />
          <span class="action-text">{{ displayFavoriteCount }}</span>
        </div>
        <div class="action-item" @click.stop="handleShare">
          <van-icon name="share-o" class="action-icon" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue';
import { showToast } from 'vant';
import { useFavoritesStore } from '@/stores/favorites';
import { useFollowsStore } from '@/stores/follows';

interface Props {
  video: any; // 视频数据
  showInfo?: boolean; // 是否显示底部信息栏
  showComment?: boolean; // 是否显示评论面板
}

const props = withDefaults(defineProps<Props>(), {
  video: null,
  showInfo: true,
  showComment: false
});

const emit = defineEmits<{
  'video-play': [];
  'video-pause': [];
  'toggle-info': [];
  'collection': [];
  'reply': [];
  'favorites': [];
  'share': [];
  'toggle-comment': [];
  'close-comment': [];
  'timeupdate': [currentTime: number];
}>();

const favoritesStore = useFavoritesStore();
const followsStore = useFollowsStore();

// 点赞状态
const isLiked = ref(false);
const likeCountIncrement = ref(0);

// 收藏数字增量
const favoriteCountIncrement = ref(0);

// 评论数字增量
const replyCountIncrement = ref(0);

// DOM引用
const videoPlayerRef = ref<HTMLVideoElement | null>(null);
const descElement = ref<HTMLElement | null>(null);

// 视频播放状态
const isVideoPlaying = ref(false);
const showPlayIcon = ref(false);
let playIconTimer: number | null = null;
let isAutoPlaying = false; // 是否正在自动播放中，防止并发调用
let abortController: AbortController | null = null; // 用于取消之前的播放请求

// 描述展开/收起状态
const isDescExpanded = ref(false);
const showExpandButton = ref(false);

// 计算属性
const videoPlayUrl = computed(() => {
  // 获取视频播放地址
  const video = props.video;
  if (!video) return '';
  return video.playUrl || video.playInfo?.url || video.url || '';
});

const description = computed(() => {
  // 获取描述文本
  return props.video?.description || props.video?.title || '';
});

const collectionCount = computed(() => {
  // 获取收藏数
  return props.video?.consumption?.collectionCount || 0;
});

// 格式化数字显示（大于10000转换为W格式）
const formatCount = (count: number | undefined | null): string => {
  if (!count || count === 0) return '0';
  if (count >= 10000) {
    const w = count / 10000;
    // 保留一位小数，如果小数部分为0则不显示小数
    const decimal = w % 1;
    if (decimal === 0) {
      return `${Math.floor(w)}W`;
    }
    // 保留一位小数
    return `${w.toFixed(1)}W`;
  }
  return count.toString();
};

// 格式化后的收藏数
const formattedCollectionCount = computed(() => {
  return formatCount(collectionCount.value);
});

// 显示的点赞数（原始值 + 增量）
const displayCollectionCount = computed(() => {
  return formatCount(collectionCount.value + likeCountIncrement.value);
});

const replyCount = computed(() => {
  // 获取评论数
  return props.video?.consumption?.replyCount || 0;
});

// 显示的评论数（原始值 + 增量）
const displayReplyCount = computed(() => {
  return formatCount(replyCount.value + replyCountIncrement.value);
});

const realCollectionCount = computed(() => {
  // 获取真实收藏数（与视频详情页保持一致）
  return props.video?.consumption?.realCollectionCount || 0;
});

// 显示的收藏数（原始值 + 增量）
const displayFavoriteCount = computed(() => {
  return formatCount(realCollectionCount.value + favoriteCountIncrement.value);
});

// 检查是否已收藏
const isFavorited = computed(() => {
  if (!props.video?.id) return false;
  return favoritesStore.isFavorited(props.video.id);
});

// 检查是否已关注
const isFollowed = computed(() => {
  if (!props.video?.author?.id) return false;
  return followsStore.isFollowed(props.video.author.id);
});

// 处理视频播放事件
const handleVideoPlay = () => {
  isVideoPlaying.value = true;
  showPlayIcon.value = false;
  if (playIconTimer) {
    clearTimeout(playIconTimer);
    playIconTimer = null;
  }
  emit('video-play');
};

// 处理视频暂停事件
const handleVideoPause = () => {
  isVideoPlaying.value = false;
  emit('video-pause');
};

// 处理视频播放进度更新
const handleTimeUpdate = () => {
  if (videoPlayerRef.value) {
    const currentTime = Math.floor(videoPlayerRef.value.currentTime);
    emit('timeupdate', currentTime);
  }
};

// 自动播放视频的函数
const autoPlayVideo = async () => {
  // 防止并发调用
  if (isAutoPlaying) {
    return;
  }

  await nextTick();
  if (!videoPlayerRef.value || !props.video) {
    return;
  }

  const video = videoPlayerRef.value;
  const currentVideo = props.video;

  // 标记为正在自动播放
  isAutoPlaying = true;
  abortController = new AbortController();

  try {
    // 先暂停所有其他视频
    const allVideos = document.querySelectorAll('video');
    allVideos.forEach((v) => {
      if (v !== video) {
        v.pause();
      }
    });

    // 等待一小段时间，确保之前的暂停操作完成
    await new Promise(resolve => setTimeout(resolve, 50));

    // 检查视频引用是否仍然有效（可能在等待期间视频已经切换）
    if (videoPlayerRef.value !== video || props.video !== currentVideo) {
      return;
    }

    // 如果视频已被暂停，先加载
    if (video.paused) {
      video.load();
      // 再次等待加载
      await new Promise(resolve => setTimeout(resolve, 100));
    }

    // 再次检查视频引用是否仍然有效
    if (videoPlayerRef.value !== video || props.video !== currentVideo) {
      video.pause();
      return;
    }

    // 设置当前视频为静音并播放
    video.muted = true;

    const playPromise = video.play();
    if (playPromise !== undefined) {
      await playPromise;
    }

    // 最后一次检查视频引用是否仍然有效
    if (videoPlayerRef.value !== video || props.video !== currentVideo) {
      video.pause();
      return;
    }

    isVideoPlaying.value = true;
    showPlayIcon.value = false;
  } catch (error: any) {
    // 忽略 AbortError 和其他预期错误（这些错误通常是因为快速切换导致的）
    if (error?.name === 'AbortError') {
      // 这是预期的，忽略
    } else if (error?.name === 'NotAllowedError') {
      // 浏览器策略不允许自动播放，这是正常的
      console.warn('浏览器不允许自动播放');
    } else {
      // 其他错误才记录
      console.error('自动播放失败:', error);
    }
    isVideoPlaying.value = false;
  } finally {
    // 重置标志
    isAutoPlaying = false;
    abortController = null;
  }
};

// 处理视频加载完成事件
const handleVideoLoaded = async () => {
  await autoPlayVideo();
};

// 处理视频点击事件：如果评论显示则收起评论，否则切换播放/暂停
const handleVideoClick = (e: MouseEvent) => {
  // 阻止事件冒泡，避免触发其他点击事件
  e.stopPropagation();

  // 如果评论面板正在显示，点击视频收起评论
  if (props.showComment) {
    emit('close-comment');
    return;
  }

  // 否则正常处理播放/暂停
  if (!videoPlayerRef.value) return;

  if (isVideoPlaying.value) {
    // 如果正在播放，则暂停
    videoPlayerRef.value.pause();
    showPlayIcon.value = true;
    // 3秒后自动隐藏播放图标
    if (playIconTimer) {
      clearTimeout(playIconTimer);
    }
    playIconTimer = window.setTimeout(() => {
      showPlayIcon.value = false;
    }, 3000);
  } else {
    // 如果暂停，则播放
    videoPlayerRef.value.play();
    showPlayIcon.value = false;
    if (playIconTimer) {
      clearTimeout(playIconTimer);
      playIconTimer = null;
    }
  }
};

// 处理点赞点击
const handleCollection = () => {
  if (!props.video) return;

  if (!isLiked.value) {
    // 点赞：数字加一
    isLiked.value = true;
    likeCountIncrement.value = 1;
  } else {
    // 取消点赞：数字减一
    isLiked.value = false;
    likeCountIncrement.value = 0;
  }
  emit('collection');
};

// 处理评论点击：触发评论面板显示/隐藏
const handleReply = () => {
  if (!props.video) return;

  // 评论数加一（每次点击评论都增加，因为打开评论面板表示用户进行了评论操作）
  replyCountIncrement.value += 1;

  emit('reply');
  emit('toggle-comment');
};

// 处理收藏点击：收藏/取消收藏
const handleFavorites = () => {
  if (!props.video) return;

  // 检查登录状态
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  if (!isLoggedIn) {
    showToast('请先登录');
    emit('favorites');
    return;
  }

  const wasFavorited = isFavorited.value;
  const success = favoritesStore.toggleFavorite(props.video);
  if (success) {
    if (!wasFavorited) {
      // 刚收藏，数字加一
      favoriteCountIncrement.value += 1;
      showToast('已收藏');
    } else {
      // 取消收藏，数字减一
      favoriteCountIncrement.value = Math.max(0, favoriteCountIncrement.value - 1);
      showToast('已取消收藏');
    }
  }
  emit('favorites');
};

// 处理分享点击：复制分享链接到剪贴板
const handleShare = () => {
  const video = props.video;
  if (!video) return;

  // 构建分享链接和文本
  const linkUrl = `https://www.eyepetizer.net/detail.html?vid=${video.id || ''}&utm_campaign=routine&utm_medium=share&utm_source=others&uid=0&resourceType=${video.resourceType || 'video'}`;
  const shareText = `${video.author?.name || ''} 在开眼发表了作品：\n「${description.value}」\n${linkUrl}`;

  // 使用 Clipboard API 或兼容方法复制到剪贴板
  if (navigator.clipboard) {
    navigator.clipboard.writeText(shareText).then(() => {
      showToast('分享链接已复制到剪贴板');
    });
  } else {
    // 兼容旧浏览器：使用 textarea 方式复制
    const textarea = document.createElement('textarea');
    textarea.value = shareText;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    showToast('分享链接已复制到剪贴板');
  }
  emit('share');
};

// 处理关注点击
const handleFollow = () => {
  if (!props.video || !props.video.author) return;

  // 检查登录状态
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  if (!isLoggedIn) {
    showToast('请先登录');
    return;
  }

  const author = {
    id: props.video.author.id || props.video.author.userId || '',
    name: props.video.author.name || '未知',
    icon: props.video.author.icon || '',
    description: props.video.author.description || ''
  };

  if (!author.id) {
    showToast('作者信息不完整');
    return;
  }

  const wasFollowed = isFollowed.value;
  const success = followsStore.toggleFollow(author);

  if (success) {
    if (!wasFollowed) {
      showToast('关注成功');
    } else {
      showToast('已取消关注');
    }
  }
};

// 检查文本是否超出两行
const checkIfTextOverflow = async () => {
  await nextTick();
  if (descElement.value && description.value) {
    // 保存当前展开状态
    const originalExpanded = isDescExpanded.value;

    // 临时设置为折叠状态来检查
    isDescExpanded.value = false;
    await nextTick();

    // 获取折叠状态下的实际内容高度和显示区域高度
    const scrollHeight = descElement.value.scrollHeight;
    const clientHeight = descElement.value.clientHeight;

    // 计算2行高度
    const lineHeight = parseFloat(getComputedStyle(descElement.value).lineHeight) || (parseFloat(getComputedStyle(descElement.value).fontSize) * 1.5);
    const maxHeight = lineHeight * 2;

    // 判断是否超出2行
    showExpandButton.value = scrollHeight > maxHeight;

    // 恢复原展开状态
    isDescExpanded.value = originalExpanded;
    await nextTick();
  } else {
    showExpandButton.value = false;
  }
};

// 切换展开/收起
const toggleDescExpand = async () => {
  if (!descElement.value) return;

  if (!isDescExpanded.value) {
    // 展开动画
    // 先设置展开状态以获取完整内容
    isDescExpanded.value = true;
    await nextTick();

    if (descElement.value) {
      // 获取实际内容高度
      const actualHeight = descElement.value.scrollHeight;
      // 先设置为当前高度（2行高度）
      const lineHeight = parseFloat(getComputedStyle(descElement.value).lineHeight) || (parseFloat(getComputedStyle(descElement.value).fontSize) * 1.5);
      const currentHeight = lineHeight * 2;
      descElement.value.style.maxHeight = `${currentHeight}px`;

      // 强制重排，然后设置为目标高度，触发动画
      await nextTick();
      requestAnimationFrame(() => {
        if (descElement.value) {
          descElement.value.style.maxHeight = `${actualHeight}px`;
        }
      });
    }
  } else {
    // 收起动画
    if (descElement.value) {
      // 获取当前实际高度
      const currentHeight = descElement.value.scrollHeight;
      descElement.value.style.maxHeight = `${currentHeight}px`;

      await nextTick();

      // 计算2行高度
      const lineHeight = parseFloat(getComputedStyle(descElement.value).lineHeight) || (parseFloat(getComputedStyle(descElement.value).fontSize) * 1.5);
      const targetHeight = lineHeight * 2;

      // 设置目标高度，触发收起动画
      requestAnimationFrame(() => {
        if (descElement.value) {
          descElement.value.style.maxHeight = `${targetHeight}px`;

          // 动画结束后，切换状态并清除内联样式
          setTimeout(() => {
            isDescExpanded.value = false;
            nextTick(() => {
              if (descElement.value) {
                descElement.value.style.maxHeight = '';
              }
            });
          }, 400); // 等待动画完成（0.4s）
        }
      });
    }
  }
};

// 监听 video 变化，切换视频时自动播放
watch(() => props.video, (newVideo) => {
  // 切换视频时重置展开状态
  isDescExpanded.value = false;
  showExpandButton.value = false;
  // 切换视频时重置增量
  likeCountIncrement.value = 0;
  favoriteCountIncrement.value = 0;
  replyCountIncrement.value = 0;
  isLiked.value = false;

  if (newVideo) {
    // 使用 nextTick 确保 DOM 已更新
    nextTick(() => {
      autoPlayVideo();
      // 检查文本是否溢出
      checkIfTextOverflow();
    });
  } else {
    // 如果没有视频，确保视频暂停
    if (videoPlayerRef.value) {
      videoPlayerRef.value.pause();
      isVideoPlaying.value = false;
    }
  }
}, { deep: true, immediate: true });

// 监听描述文本变化，检查文本是否超出
watch(() => description.value, () => {
  if (description.value) {
    checkIfTextOverflow();
  }
}, { immediate: true });

// 监听视频 URL 变化，自动播放（只在 URL 真正变化时调用，避免重复）
let lastVideoUrl = '';
watch(() => videoPlayUrl.value, (newUrl) => {
  if (newUrl && props.video && newUrl !== lastVideoUrl) {
    lastVideoUrl = newUrl;
    nextTick(() => {
      autoPlayVideo();
    });
  }
});

defineExpose({
  videoPlayerRef
});
</script>

<style scoped lang="less">
.video-card-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #000;
  overflow: hidden;
}

.video-container {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;

  .video-player {
    width: 100%;
    height: 100%;
    object-fit: contain;
    background-color: #000;
    outline: none;
    border: none;

    &::-webkit-media-controls {
      display: none !important;
    }

    &::-webkit-media-controls-enclosure {
      display: none !important;
    }

    &::-webkit-media-controls-panel {
      display: none !important;
    }

    &::-webkit-media-controls-play-button {
      display: none !important;
    }

    &::-webkit-media-controls-start-playback-button {
      display: none !important;
    }
  }

  .play-icon-overlay {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 5;
    pointer-events: none;
    display: flex;
    align-items: center;
    justify-content: center;

    .play-icon-large {
      font-size: 40px;
      color: rgba(255, 255, 255, 0.9);
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      padding: 10px;
      box-sizing: border-box;
    }
  }
}

.info-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.5));
  padding: 13px 14px 0;
  padding-right: 70px;
  /* 为右侧按钮留出空间 */
  box-sizing: border-box;
  transition: opacity 0.3s ease, transform 0.3s ease;
  display: flex;
  align-items: flex-end;

  &.hidden {
    opacity: 0;
    transform: translateY(100%);
    pointer-events: none;
  }
}

.info-content {
  flex: 1;
  min-width: 0;
  /* 允许内容收缩 */
}

.author-name {
  font-size: 14px;
  color: #fff;
  font-weight: 500;
  margin-bottom: 8px;
}

.description-wrapper {
  position: relative;
  margin-top: 0;
  padding-bottom: 6px;
}

.description {
  font-size: 13px;
  color: #fff;
  line-height: 1.5;
  padding: 0;
  overflow: hidden;
  max-height: 3em;
  transition: max-height 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;

  &.expanded {
    display: block;
    -webkit-line-clamp: unset;
    text-overflow: clip;
  }
}

.expand-btn {
  position: absolute;
  right: 0;
  bottom: 0;
  background: linear-gradient(to right, transparent, rgba(0, 0, 0, 0.8) 30%);
  padding: 2px 0 2px 15px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  color: #fff;
  font-size: 13px;
  opacity: 0.9;
  transition: opacity 0.2s;

  &:hover {
    opacity: 1;
  }

  &:active {
    opacity: 0.7;
  }
}

.action-bar {
  position: absolute;
  right: 14px;
  bottom: 13px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 0;
  z-index: 10;

  .user-avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    margin-bottom: 0;
    position: relative;

    .avatar-wrapper {
      position: relative;
      width: 48px;
      height: 48px;

      .avatar {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
        border: 2px solid rgba(255, 255, 255, 0.3);
      }
    }

    .follow-btn {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: #ff4757;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: transform 0.2s, background-color 0.2s;
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translate(-50%, 50%);

      &:active {
        transform: scale(0.9);
      }

      .follow-icon {
        font-size: 12px;
        color: #fff;
        font-weight: bold;
      }
    }
  }

  .action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 5px;
    cursor: pointer;
    padding: 0;

    &.favorited {
      .action-icon {
        color: #ffd700;
      }
    }

    &.liked {
      .action-icon {
        color: #ff6b6b;
      }
    }

    .action-icon {
      font-size: 24px;
      color: #fff;
    }

    .action-text {
      font-size: 12px;
      color: #fff;
      font-weight: 500;
    }
  }
}
</style>
